var pictureSource; // picture source
var destinationType; // sets the format of returned value
var siteUrl = 'http://cirpho.com/index.php/cirpho/';
var imgSource = '';
var imgUri = '';
var servers = null;
var screenStatus = 0;
var maxWidth = 0;
var maxHeight = 0;

// Wait for PhoneGap to connect with the device
//
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener('touchmove', function(e) {
	e.preventDefault();
}, false);

// PhoneGap is ready to be used!
//

  document.addEventListener("backbutton", function () {
	  if(screenStatus == 0){
		  return;
	  }else if(screenStatus == 1){
		  displayMenu();
	  }else if(screenStatus == 2){
		  jQuery.mobile.changePage(jQuery("#image"), {
				transition : "pop"
			});
		  screenStatus = 1;
	  }else if(screenStatus == 3){
		  displayCategories();
	  }else if(screenStatus == 4){
		  jQuery.mobile.changePage(jQuery("#main"), {
				transition : "pop"
			});
	  }
  },
  false);
 

function onDeviceReady() {
	pictureSource = navigator.camera.PictureSourceType;
	destinationType = navigator.camera.DestinationType;
	
	setMaxWidthHeight();
		
	$howtouse = localStorage.getItem('howtouse');
	if ($howtouse == 1) {
		capturePhoto();
		// getPhoto(pictureSource.PHOTOLIBRARY);
	} else {
		//jQuery('#howtouse-close').bind('click', closeHowToUse);
		displayHowToUse();
	}
}

// Get screen size

function getScreenWidth() {
	var screenW = 640, screenH = 480;
	if (parseInt(navigator.appVersion) > 3) {
		screenW = screen.width;
		screenH = screen.height;
	} else if (navigator.appName == "Netscape"
			&& parseInt(navigator.appVersion) == 3 && navigator.javaEnabled()) {
		var jToolkit = java.awt.Toolkit.getDefaultToolkit();
		var jScreenSize = jToolkit.getScreenSize();
		screenW = jScreenSize.width;
		screenH = jScreenSize.height;
	}
	return screenW;
}

function getScreenHeight() {
	var screenW = 640, screenH = 480;
	if (parseInt(navigator.appVersion) > 3) {
		screenW = screen.width;
		screenH = screen.height;
	} else if (navigator.appName == "Netscape"
			&& parseInt(navigator.appVersion) == 3 && navigator.javaEnabled()) {
		var jToolkit = java.awt.Toolkit.getDefaultToolkit();
		var jScreenSize = jToolkit.getScreenSize();
		screenW = jScreenSize.width;
		screenH = jScreenSize.height;
	}
	return screenH;
}


function checkDisplayImageComplete(callback) {
	if (jQuery(".jcrop-holder").length == 0){
		setTimeout(function() {
			checkDisplayImageComplete(callback);
		}, 50);
	} else {
		if (callback) {
			callback();
		}
	}
}

// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
	
	screenStatus = 1;
	imgUri = imageURI;
	imageHtml = '<img id="image-data" src="'+imageURI+'" />';
	jQuery("#image-data-wrapper").html(imageHtml);
		
	screenHeight = getScreenHeight();
	screenWidth = getScreenWidth();

	jQuery.mobile.changePage(jQuery("#image"), {
		transition : "pop"
	});
	
	subHeight = jQuery("#top-content-image").height() + jQuery("#header-wrapper").height() + 40 + jQuery("#done-button-wrapper").height() + jQuery(".bottom-content-image").height();
	//365
	minHeight = getScreenHeight() - jQuery("#top-content-image").height() - jQuery("#bottom-content").height() +5;
	jQuery("#main-content").css("height", minHeight + "px");
	
	jQuery("#image-data-wrapper").css('height', screenHeight - subHeight);
	
	jQuery('#image-data').load(function () {
        jQuery(function() {
    		jQuery('#image-data').Jcrop( {
    			aspectRatio : 0,
    			minSize: [50, 50],
    			setSelect : [ screenWidth/2 - maxWidth/2,  (screenHeight - subHeight)/2 - maxHeight/2,  screenWidth/2 + maxWidth/2,  (screenHeight-subHeight)/2 + maxHeight/2],
    			//setSelect : [ 5,  5, maxWidth, maxHeight ],
    			onSelect : updateCoords
    		});

    	});    	
    });
		
	//jQuery.mobile.changePage(jQuery("#image"), {
	//	transition : "pop"
	//});
	checkDisplayImageComplete(function(){
		//alert((screenWidth - jQuery(".jcrop-holder").width())/2);
		//jQuery(".jcrop-holder").css('margin-left', (screenWidth - jQuery(".jcrop-holder").width())/2);
		jcropHolderWidth = jQuery(".jcrop-holder").width();
		jcropHolderHeight = jQuery(".jcrop-holder").height();
		jQuery("#image-data-wrapper").css('padding-left', (screenWidth - jQuery(".jcrop-holder").width())/2);
		jQuery("#image-data-wrapper").css('padding-top', (screenHeight - subHeight - jQuery(".jcrop-holder").height())/2);
		jQuery("#image-data-wrapper").css('height', screenHeight - subHeight - (screenHeight - subHeight - jQuery(".jcrop-holder").height())/2);
		jQuery(function() {
    		jQuery('#image-data').Jcrop( {
    			aspectRatio : 0,
    			minSize: [50, 50],
    			setSelect : [ jcropHolderWidth/2 - maxWidth/2,  jcropHolderHeight/2 - maxHeight/2,  jcropHolderWidth/2 + maxWidth/2,  jcropHolderHeight/2 + maxHeight/2],
    			//setSelect : [ 5,  5, maxWidth, maxHeight ],
    			onSelect : updateCoords
    		});

    	});
        jQuery("#image-data-wrapper").css('text-align', 'center');
        jQuery('#x').val(Math.round(jcropHolderWidth/2 - maxWidth/2));
    	jQuery('#y').val(Math.round(jcropHolderHeight/2 - maxHeight/2));
    	jQuery('#w').val(maxWidth);
    	jQuery('#h').val(maxHeight);
	});
}

function updateCoords(c) {
	jQuery('#x').val(c.x);
	jQuery('#y').val(c.y);
	jQuery('#w').val(c.w);
	jQuery('#h').val(c.h);
}


function checkCoords() {
	if (parseInt(jQuery('#w').val()))
		return true;
	alert('Please select a crop region then press submit.');
	return false;
}


var selectionExists;

// Update form inputs
function updateForm(crop) {
	console.log(crop.selectionX);
	alert(crop.selectionX);
	alert(crop.selectionY);
	alert(crop.selectionWidth);
	alert(crop.selectionHeight);
	jQuery('input#x').val(crop.selectionX);
	jQuery('input#y').val(crop.selectionY);
	jQuery('input#width').val(crop.selectionWidth);
	jQuery('input#height').val(crop.selectionHeight);

	selectionExists = crop.selectionExists();
};

// A button will call this function
//
function capturePhoto() {
	jQuery("#howtouse").css("display", "none");
	jQuery("#main").css("display", "none");
	// Take picture using device camera and retrieve image as base64-encoded
	// string
	navigator.camera.getPicture(onPhotoURISuccess, onFail, {
		quality : 25,
		allowEdit : true,
		targetWidth : 1080,
		destinationType : destinationType.FILE_URI
	});

}

// A button will call this function
//
function capturePhotoEdit() {
	jQuery("#menu-wrapper").css("display", "none");

	// Take picture using device camera, allow edit, and retrieve image as
	// base64-encoded string
	navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
		quality : 25,
		allowEdit : true
	});

}

// A button will call this function
//
function getPhoto(source) {
	jQuery("#main").css("display", "none");
	jQuery("#howtouse").css("display", "none");
	// Retrieve image file location from specified source
	navigator.camera.getPicture(onPhotoURISuccess, onFail, {
		quality : 25,
		destinationType : destinationType.FILE_URI,
		sourceType : source
	});

}

// Called if something bad happens.
// 
function onFail(message) {
	displayMenu();
}

// Display content after get image
function dispayAfterGetImage() {
	jQuery("#menu-wrapper").css("display", "none");
	jQuery("#footer-wrapper").css("display", "block");
	jQuery("#header-left > span").html("Camera frame");
	jQuery("#image").css("display", "block");
	jQuery("#search-result").css("display", "none");
	jQuery("#categories").css("display", "none");
	jQuery('#header-right').css("display", "none");
	jQuery("#how-to-use").css("display", "none");

}

// Display Menu
function displayMenu() {
	jQuery("#main").css("display", "");
	screenStatus = 0;
	jQuery.mobile.changePage(jQuery("#main"), {
		transition : "pop"
	});
	displayAterSelectMenu();
	jQuery("#menu-wrapper").css("display", "block");
	jQuery("#search-result-wrapper ul").html("");
	jQuery(".report-button").html("");
	jQuery("#search-result").css("display", "none");
	jQuery("#categories").css("display", "none");
	jQuery("#header-left > span").html("どうやって検索しますか？");
	jQuery("#header-right").css("display", "none");
	jQuery('#footer-wrapper').css("display", "none");
		
	minHeight = getScreenHeight() - jQuery("#top-content").height() - jQuery("#bottom-content").height()+5;
	jQuery("#main-content").css("height", minHeight + "px");
	return false;
}

// Success reporting
function win(r) {
	alert("Code = " + r.responseCode);
	alert("Response = " + r.response);
}

// Error reporting
function fail(message) {
	alert('Failed because: ' + message);
}
function displayAfterDisplayCategories() {
	jQuery("#image").css("display", "none");
	jQuery("#footer-wrapper").css("display", "none");
	jQuery("#header-left > span").html("何についての画像ですか？");
}

function displayAterSelectMenu() {
	jQuery('#search-result').css("display", "none");
	jQuery('#categories').css("display", "none");
	jQuery('#loadding').css("display", "none");

}

function backToCategories() {
	jQuery("#header-right a").removeClass("header-right-hover");
	jQuery('#loadding').css("display", "none");
	jQuery('#search-result-wrapper ul').html("");
	jQuery(".report-button").html("");
	jQuery('#search-result').css("display", "none");
	jQuery('#categories').css("display", "block");
	jQuery('#categories').html("");
	jQuery("#header-right").css("display", "none");
	displayCategories();

}
function selectCategory(obj) {
	screenStatus = 3;
	jQuery('#categories').css("display", "none");
	jQuery('#header-right').css("display", "block");
	jQuery("#header-left > span").html("検索結果");
	jQuery("#header-left").css("width", "40%");
	jQuery("#header-right").css("width", "50%");
	jQuery('#search-result-wrapper ul').html("");
	jQuery(".report-button").html("");
	jQuery('#search-result').css("display", "block");
	jQuery('#loadding').css("display", "block");
	jQuery('#loadding > span.loadding-text').html("検索中です…");
	categoryId = jQuery(obj).attr('id');
	serverCount = 0;
	jQuery
			.post(
					siteUrl,
					{
						categoryId : categoryId,
						image : imgSource
					},
					function(data) {
						// alert(data);
						htmlStr = '';
						var matchData = null;
						if (data != null && data != '') {
							res = eval('(' + data + ')');
							for (i = 0; i < res.length; i++) {
								if (res[i].decision_matching_rate <= res[i].matchPercent) {
									matchData = res[i];
									htmlStr1 = '<li class=\'search-result-item decision-matching-rate\'><div class=\'search-result-item-right\'><span class=\'result-title\'>'
											+ res[i].title
											+ '</span>'
											+ '<span class=\'result-url\'><a href=\''
											+ siteUrl + 'redirect/' + res[i].groupId + '/1'
											+ '\'>'
											+ res[i].comment
											+ '</a></span>';
									if( res[i].comment1 != null){
										htmlStr1 += '<span class=\'result-url\'><a href=\''
											+ siteUrl + 'redirect/' + res[i].groupId + '/2'
											+ '\'>'
											+ res[i].comment1
											+ '</a></span>';
									}
									if( res[i].comment2 != null){
										htmlStr1 += '<span class=\'result-url\'><a href=\''
											+ siteUrl + 'redirect/' + res[i].groupId + '/3'
											+ '\'>'
											+ res[i].comment2
											+ '</a></span>';
									}
									htmlStr1 += '</div><div class=\'clear\'></div></li>';
									htmlStr = htmlStr1 + htmlStr;
								} else {
									htmlStr += '<li class=\'search-result-item\'><div class=\'search-result-item-right\'><span class=\'result-title\'>'
											+ res[i].title
											+ '</span>'
											+ '<span class=\'result-url\'><a href=\''
											+ siteUrl + 'redirect/' + res[i].groupId + '/1'
											+ '\'>'
											+ res[i].comment
											+ '</a></span>';
									if( res[i].comment1 != null){
										htmlStr += '<span class=\'result-url\'><a href=\''
											+ siteUrl + 'redirect/' + res[i].groupId + '/2'
											+ '\'>'
											+ res[i].comment1
											+ '</a></span>';
									}
									if( res[i].comment2 != null){
										htmlStr += '<span class=\'result-url\'><a href=\''
											+ siteUrl + 'redirect/' + res[i].groupId + '/3'
											+ '\'>'
											+ res[i].comment2
											+ '</a></span>';
									}
									htmlStr += '</div><div class=\'clear\'></div></li>';
								}
							}
						}
						if (jQuery("#search-result-wrapper  ul  li.decision-matching-rate").length == 0) {
							jQuery('#loadding').css("display", "none");
							jQuery("#search-result-wrapper  ul").prepend(htmlStr);
							if(matchData){
								jQuery
								.post(
										siteUrl+'updatematch/'+matchData.groupId,
										{
										},
										function(data) {
											
										}
								);
							}
						}
						serverCount++;
					});

	if (servers != null) {
		for (i = 0; i < servers.length; i++) {
			// alert('http://'+ servers[i].domain_name + '/index.php/cirpho');
			jQuery
					.post(
							'http://' + servers[i].domain_name
									+ '/index.php/cirpho',
							{
								categoryId : categoryId,
								image : imgSource
							},
							function(data) {
								// alert(data);
								htmlStr = '';
								var matchData = null;
								if (data != null && data != '') {
									res = eval('(' + data + ')');
									for (i = 0; i < res.length; i++) {
										if (res[i].decision_matching_rate <= res[i].matchPercent) {
											matchData = res[i];
											htmlStr1 = '<li class=\'search-result-item decision-matching-rate\'><div class=\'search-result-item-right\'><span class=\'result-title\'>'
												+ res[i].title
												+ '</span>'
												+ '<span class=\'result-url\'><a href=\''
												+ siteUrl + 'redirect/' + res[i].groupId + '/1'
												+ '\'>'
												+ res[i].comment
												+ '</a></span>';
											if( res[i].comment1 != null){
												htmlStr1 += '<span class=\'result-url\'><a href=\''
													+ siteUrl + 'redirect/' + res[i].groupId + '/2'
													+ '\'>'
													+ res[i].comment1
													+ '</a></span>';
											}
											if( res[i].comment2 != null){
												htmlStr1 += '<span class=\'result-url\'><a href=\''
													+ siteUrl + 'redirect/' + res[i].groupId + '/3'
													+ '\'>'
													+ res[i].comment2
													+ '</a></span>';
											}
											htmlStr1 += '</div><div class=\'clear\'></div></li>';
											htmlStr = htmlStr1 + htmlStr;
										} else {
											
											htmlStr += '<li class=\'search-result-item\'><div class=\'search-result-item-right\'><span class=\'result-title\'>'
												+ res[i].title
												+ '</span>'
												+ '<span class=\'result-url\'><a href=\''
												+ siteUrl + 'redirect/' + res[i].groupId + '/1'
												+ '\'>'
												+ res[i].comment
												+ '</a></span>';
										if( res[i].comment1 != null){
											htmlStr += '<span class=\'result-url\'><a href=\''
												+ siteUrl + 'redirect/' + res[i].groupId + '/2'
												+ '\'>'
												+ res[i].comment1
												+ '</a></span>';
										}
										if( res[i].comment2 != null){
											htmlStr += '<span class=\'result-url\'><a href=\''
												+ siteUrl + 'redirect/' + res[i].groupId + '/3'
												+ '\'>'
												+ res[i].comment2
												+ '</a></span>';
										}
										htmlStr += '</div><div class=\'clear\'></div></li>';
										}
									}
								}
								//jQuery("#search-result-wrapper  ul").prepend(htmlStr);
								if (jQuery("#search-result-wrapper  ul  li.decision-matching-rate").length == 0) {
									jQuery('#loadding').css("display", "none");
									jQuery("#search-result-wrapper  ul")
											.prepend(htmlStr);
									if(matchData){
										jQuery
										.post(
												siteUrl+'updatematch/'+matchData.groupId,
												{
												},
												function(data) {
													
												}
										);
									}
								}
								serverCount++;
							});
		}
	}

	checkSearchComplete(function() {
		if (jQuery("#search-result-wrapper ul li").length > 0) {
			jQuery(".report-button")
					.html(
							'<div class=\'report-button\'><button onclick=\'report("");\'>結果が正しくなかったことを報告</button></div>');
		} else {
			jQuery("#search-result-wrapper ul").append(
					'<li><span class="no-result-span">見つかりませんでした。</span></li>');
		}
		jQuery('#loadding').css("display", "none");
		var myScroll = new iScroll('search-result');

	});

}

function checkSearchComplete(callback) {
	if (servers == null) {
		numberOfServer = 0;
	} else {
		numberOfServer = servers.length;
	}
	if ((serverCount < (numberOfServer + 1))
			&& (jQuery("#search-result-wrapper  ul  li.decision-matching-rate").length == 0)) {
		// if(serverCount < (numberOfServer + 1)){
		setTimeout(function() {
			checkSearchComplete(callback);
		}, 50);
	} else {
		if (callback) {
			callback();
		}
	}
}

function displayCategories() {
	jQuery("#main").css("display", "");
	jQuery.mobile.changePage($("#main"), {
		transition : "pop"
	});
	minHeight = getScreenHeight() - jQuery("#top-content").height() - jQuery("#bottom-content").height()+5;
	jQuery("#main-content").css("height", minHeight + "px");
	screenStatus = 2;
	jQuery('#search-result').css("display", "none");
	jQuery("#menu-wrapper").css("display", "none");
	jQuery("#header-left > span").html("何についての画像ですか？");
	jQuery("#header-left").css("width", "90%");
	jQuery("#header-right").css("display", "none");
	jQuery('#search-result-wrapper ul').html("");
	jQuery(".report-button").html("");
	jQuery('#categories').html("");
	jQuery('#categories').css("display", "block");
	jQuery('#loadding').css("display", "block");
	jQuery('#loadding > span.loadding-text').html("ロード...");
	
	jQuery
			.post(
					siteUrl + 'category',
					function(data) {
						htmlStr = '<div id="categories-wrapper"><ul>';
						otherCategory = '';
						// alert(data);
						if (data != null && data != '') {
							resAll = eval('(' + data + ')');
							res = resAll.category;
							servers = resAll.server;
							j = 0;
							for (i = 0; i < res.length; i++) {
								if (res[i].id == 23) {
									otherCategory = '<div class="other-category"><a id=\'23\' ><span>'
											+ res[i].name + '</span></a></div>';
								} else {
									if (j % 2) {
										htmlStr += '<li id=\''
												+ res[i].id
												+ '\' class=\'categoryItem-right\'><span>'
												+ res[i].name
												//+ '</span></li><div class=\'clear\'></div>';
												+ '</span></li>';
									} else {
										htmlStr += '<li id=\''
												+ res[i].id
												+ '\' class=\'categoryItem-left\'><span>'
												+ res[i].name + '</span></li>';
									}
									j++;
								}
							}
						}
						htmlStr += '</ul>';
						htmlStr += '<div class="clear"></div>';
						// htmlStr += '<div class="other-category"><button
						// id=\'0\'
						// onclick=\'selectCategory(this);\'>Other</button></div>';
						htmlStr += otherCategory;
						htmlStr += '</div>';
						jQuery('#loadding').css("display", "none");
						jQuery('#categories').html(htmlStr);
						jQuery("#categories ul li").bind("tap",function(){
							jQuery(this).addClass("categories-hover");
						});
						jQuery("#categories ul li").click(function(){
							obj = this;
							setTimeout(function() {
								selectCategory(obj);
							}, 80);
						});
						
						jQuery(".other-category a").bind("tap",function(){
							jQuery(this).addClass("other-category-hover");
							jQuery(".other-category a span").addClass("other-category-span-hover");
						});
						jQuery(".other-category a").click(function(){
							obj = this;
							setTimeout(function() {
								selectCategory(obj);
							}, 80);
						});
						
						var myScroll = new iScroll('categories', {
							vScrollbar : true
						});
					});
					
}

function cropImage() {
	//alert(jQuery('#x').val());
	//alert(jQuery('#y').val());
	//alert(jQuery('#w').val());
	//alert(jQuery('#h').val());

	//alert(jQuery(".jcrop-holder").height());
	//alert(jQuery(".jcrop-holder").width());
	
	window.plugins.cirphoCamera.camera({
		imageUri: imgUri,
		imageHeight: jQuery(".jcrop-holder").height(),
		imageWidth: jQuery(".jcrop-holder").width(),
		x: jQuery('#x').val(),
		y: jQuery('#y').val(),
		targetWidth: jQuery('#w').val(),
		targetHeight: jQuery('#h').val()
	},
	// navigator.directoryListing.list("/sdcard",

	function(r) {
		onCropSuccess(r);
	},

	function(e) {
		onCropFail(e)
	}

	);
}

function onCropSuccess(result){
	imgSource = result;
	jQuery("#done-button a img").attr("src", "images/ok-button.png");
	displayCategories();
}

function onCropFail(e){
	
}

function report(result) {
	//jQuery('#loadding').css("display", "block");
	//jQuery('#loadding > span.loadding-text').html("送信...");
	jQuery.post(siteUrl + 'report', {
		image : imgSource
	}, function(data) {
		jQuery('#loadding').css("display", "none");
		//alert("送信完了\nご報告ありがとうございます");
		confirm("ご報告ありがとうございます", function () {
		});
	}).error(function() { alert("error"); });
}

function confirm(message, callback) {
	jQuery('#confirm').modal({
		closeHTML: "<a href='#' title='Close' class='modal-close'></a>",
		position: ["30%",],
		overlayId: 'confirm-overlay',
		containerId: 'confirm-container', 
		onShow: function (dialog) {
			var modal = this;

			jQuery('.message', dialog.data[0]).append(message);

			// if the user clicks "yes"
			jQuery('.yes', dialog.data[0]).click(function () {
				// call the callback
				if ($.isFunction(callback)) {
					callback.apply();
				}
				// close the dialog
				modal.close(); // or $.modal.close();
			});
		}
	});
}

function howToUse() {
	jQuery("#menu-wrapper").css("display", "none");
	jQuery("#image").css("display", "none");
	jQuery(".report-button").html("");
	jQuery("#search-result-wrapper ul").html("");
	jQuery("#search-result").css("display", "none");
	jQuery("#categories").html("");
	jQuery("#categories").css("display", "none");
	jQuery("#header-left > span").html("How to use");
	jQuery("#header-right").css("display", "none");
	jQuery('#footer-wrapper').css("display", "none");
	jQuery('#loadding').css("display", "block");
	jQuery('#loadding > span.loadding-text').html("ロード...");
	jQuery("#how-to-use").css("display", "block");
	jQuery.post(siteUrl + 'howtouse', function(data) {
		if (data != null && data != '') {
			// alert(data);
			res = eval('(' + data + ')');
			jQuery("#how-to-use").html(
					'<div id="howtouse-wrapper">' + res.value + '</div>');
		}
		jQuery('#loadding').css("display", "none");
		var myScroll = new iScroll('how-to-use', {
			vScrollbar : true
		});

	});
	return false;
}

function setMaxWidthHeight(){
	jQuery.post(siteUrl + 'getsize', function(data) {
		if (data != null && data != '') {
			//alert(data);
			res = eval('(' + data + ')');
			maxWidth = res.width;
			maxHeight = res.height;
		}
	});
}

function howToUseClick() {
	jQuery('#howtouse-close').unbind('click', closeHowToUse);
	jQuery('#howtouse-close').bind('click', backToMainPage);
	displayHowToUse();
}

function displayHowToUse() {
	screenStatus = 4;
	jQuery("#howtouse").css("display", "");
	$howtouse = localStorage.getItem('howtouse');
	if (jQuery("#how-to-use").html() == "") {
		//jQuery('#howtouse-loadding').css("display", "block");
		//jQuery('#howtouse-loadding > span.loadding-text').html("ロード...");
		
		jQuery("#how-to-use").html('<div id="howtouse-loadding">'
					+'<span><img src="images/loading.gif" /></span><span class="loadding-text">ロード...</span>'
					+'</div>');
		
		jQuery.mobile.changePage($("#howtouse"), {
			transition : "pop"
		});
		
		minHeight = getScreenHeight() - jQuery("#top-content-howtouse").height() - jQuery("#header-wrapper").height() - jQuery("#checkbox-howtouse-wrapper").height() - jQuery(".bottom-content-howtouse").height()-35;
		
		jQuery("#howtouse-wrapper").css("height", minHeight + "px");
		
		if ($howtouse == 1) {
			jQuery("#checkbox-howtouse").attr("checked", true).checkboxradio(
					"refresh");
		} else {
			jQuery("#checkbox-howtouse").attr("checked", false).checkboxradio(
					"refresh");
		}
		
		jQuery.post(siteUrl + 'howtouse', function(data) {
			if (data != null && data != '') {
				// alert(data);
				res = eval('(' + data + ')');
				jQuery("#how-to-use").html(res.value);
			}
			jQuery('#howtouse-loadding').css("display", "none");

			var howtouseScroll = new iScroll('howtouse-wrapper', {
				vScrollbar : true
			});
		});
	} else {
		if ($howtouse == 1) {
			jQuery("#checkbox-howtouse").attr("checked", true).checkboxradio(
					"refresh");
		} else {
			jQuery("#checkbox-howtouse").attr("checked", false).checkboxradio(
					"refresh");
		}
		jQuery.mobile.changePage($("#howtouse"), {
			transition : "pop"
		});
	}
}
function closeHowToUse() {
	if (jQuery('#checkbox-howtouse').is(':checked')) {
		localStorage.setItem('howtouse', 1);
	} else {
		localStorage.setItem('howtouse', 0);
	}
	capturePhoto();
}
function howToUseChange(){
	if (jQuery('#checkbox-howtouse').is(':checked')) {
		localStorage.setItem('howtouse', 1);
	} else {
		localStorage.setItem('howtouse', 0);
	}
}
function backToMainPage() {
	if (jQuery('#checkbox-howtouse').is(':checked')) {
		localStorage.setItem('howtouse', 1);
	} else {
		localStorage.setItem('howtouse', 0);
	}
	jQuery("#howtouse-close").removeClass("header-right-hover");
	jQuery("#main").css("display", "");
	jQuery.mobile.changePage($("#main"), {
		transition : "pop"
	});
	minHeight = getScreenHeight() - jQuery("#top-content").height() - jQuery("#bottom-content").height() +5;
	jQuery("#main-content").css("height", minHeight + "px");
}
function exit() {
	navigator.app.exitApp();
}
jQuery(document).ready(function(){

	jQuery(".menu-item-take-shot a").click(function(){
		capturePhoto();
		jQuery(".menu-item-take-shot a img").attr("src", "images/take-shot-bg.png");
	});
	
	jQuery(".menu-item-take-shot a").tap(function(){
		jQuery(".menu-item-take-shot a img").attr("src", "images/take-shot-act-bg.png");
		setTimeout(function() {
			jQuery(".menu-item-take-shot a img").attr("src", "images/take-shot-bg.png");
		}, 200);
	});
		
	jQuery(".menu-item-gallery a").click(function(){
		getPhoto(pictureSource.PHOTOLIBRARY);
		jQuery(".menu-item-gallery a img").attr("src", "images/gallery-bg.png");
	});
	
	jQuery(".menu-item-gallery a").tap(function(){
		jQuery(".menu-item-gallery a img").attr("src", "images/gallery-act-bg.png");
		setTimeout(function() {
			jQuery(".menu-item-gallery a img").attr("src", "images/gallery-bg.png");
		}, 200);
	});
	
	jQuery(".menu-item-exit a").click(function(){
		exit();
		jQuery(".menu-item-exit a img").attr("src", "images/exit-bg.png");
	});
	
	jQuery(".menu-item-exit a").tap(function(){
		jQuery(".menu-item-exit a img").attr("src", "images/exit-act-bg.png");
		setTimeout(function() {
			jQuery(".menu-item-exit a img").attr("src", "images/exit-bg.png");
		}, 200);
	});
	
	jQuery("#bottom-content a.display-menu").click(function(){
		displayMenu();
		jQuery("#bottom-content a.display-menu img").attr("src", "images/menu-bg.png");
	});
	
	jQuery(".topcontent-left img").click(function(){
		displayMenu();
	});
	
	jQuery("#bottom-content a.display-menu").tap(function(){
		jQuery("#bottom-content a.display-menu img").attr("src", "images/menu-act-bg.png");
		setTimeout(function() {
			jQuery("#bottom-content a.display-menu img").attr("src", "images/menu-bg.png");
		}, 200);
	});
	
	jQuery("#bottom-content a.how-to-use-page").click(function(){
		jQuery("#howtouse").css("display", "");
		displayHowToUse();
		jQuery("#bottom-content a.how-to-use-page img").attr("src", "images/how-to-use.png");
	});
	
	jQuery("#bottom-content a.how-to-use-page").tap(function(){
		jQuery("#bottom-content a.how-to-use-page img").attr("src", "images/how-to-use-act-bg.png");
		setTimeout(function() {
			jQuery("#bottom-content a.how-to-use-page img").attr("src", "images/how-to-use.png");
		}, 200);
	});
	
	jQuery("#done-button a").click(function(){
		cropImage();
		jQuery("#done-button a img").attr("src", "images/ok-button-act.png");
	});
	
	jQuery("#done-button a").tap(function(){
		jQuery("#done-button a img").attr("src", "images/ok-button-act.png");
		setTimeout(function() {
			jQuery("#done-button a img").attr("src", "images/ok-button.png");
		}, 200);
	});
	
	jQuery("#header-right a").click(function(){
		setTimeout(function() {
			backToCategories();
		}, 80);
	});
	
	jQuery("#header-right a").tap(function(){
		jQuery("#header-right a").addClass("header-right-hover");
	});
	
	jQuery("#howtouse-close").click(function(){
		setTimeout(function() {
			backToMainPage();
		}, 80);
	});
	
	jQuery("#howtouse-close").tap(function(){
		jQuery("#howtouse-close").addClass("header-right-hover");
	});
	
	
});